package com.tlgen.modules.dept.service.impl;

import com.tlgen.common.exception.EntityExistException;
import com.tlgen.common.utils.FileUtil;
import com.tlgen.common.utils.PageUtil;
import com.tlgen.common.utils.QueryHelp;
import com.tlgen.common.utils.ValidationUtil;
import com.tlgen.modules.dept.domain.Doctors;
import com.tlgen.modules.dept.repository.DoctorsRepository;
import com.tlgen.modules.dept.service.DoctorsService;
import com.tlgen.modules.dept.service.dto.DoctorsDto;
import com.tlgen.modules.dept.service.dto.DoctorsQueryCriteria;
import com.tlgen.modules.dept.service.mapper.DoctorsMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Service
@CacheConfig(cacheNames = "Doctors")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DoctorsServiceImpl implements DoctorsService {

    private final DoctorsRepository doctorsRepository;

    private final DoctorsMapper doctorsMapper;

    public DoctorsServiceImpl(DoctorsRepository doctorsRepository, DoctorsMapper doctorsMapper) {
        this.doctorsRepository = doctorsRepository;
        this.doctorsMapper = doctorsMapper;
    }

    /**
     * 根据登记人员名称获取信息
     * @param name
     * @return
     */
    @Override
    @Cacheable(key = "'loadUserByName:'+#p0")
    public DoctorsDto findByName(String name) {
        Doctors doctors1;
        doctors1 = doctorsRepository.findByName(name);
        if(doctors1==null){
            throw new EntityExistException(Doctors.class,"Doctors",name);
        }else {
            return doctorsMapper.toDto(doctors1);
        }
    }

    /**
     * 不带条件分页查询
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(Pageable pageable) {
        return doctorsMapper.toDto(doctorsRepository.findAll(pageable).getContent());
    }


    /**
     * 带条件分页查询
     * @param criteria 条件
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(DoctorsQueryCriteria criteria, Pageable pageable) {
        Page<Doctors> page = doctorsRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(doctorsMapper::toDto));
    }

    /**
     * 带条件不分页查询
     * @param criteria 条件
     * @return
     */
    @Override
    @Cacheable
    public List<DoctorsDto> queryAll(DoctorsQueryCriteria criteria) {
        return doctorsMapper.toDto(doctorsRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    /**
     * 新增
     * @param resources /
     * @return
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public DoctorsDto create(Doctors resources) {
        if (doctorsRepository.findByName(resources.getName()) != null) {
            throw new EntityExistException(Doctors.class, "Doctors", resources.getName());
        }
        return doctorsMapper.toDto(doctorsRepository.save(resources));
    }

    /**
     * 编辑
     * @param resources /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(Doctors resources) {
        Doctors doctors = doctorsRepository.findById(resources.getId()).orElseGet(Doctors::new);
        ValidationUtil.isNull(doctors.getId(),"Doctors","id",resources.getId());

        doctors.setName(resources.getName());
        doctors.setProvince(resources.getProvince());
        doctors.setCity(resources.getCity());
        doctorsRepository.save(doctors);
    }

    /**
     * 删除
     * @param ids /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            doctorsRepository.deleteById(id);
        }
    }

    /**
     * 导出数据
     * @param response /
     * @throws IOException
     */
    @Override
    public void download(List<DoctorsDto> doctorsDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DoctorsDto doctorsDto : doctorsDtos) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("姓名", doctorsDto.getName());
            map.put("省", doctorsDto.getProvince());
            map.put("市", doctorsDto.getCity());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 根据Id查询
     * @param id /
     * @return
     */
    @Override
    @Cacheable(key = "#p0")
    public DoctorsDto findById(long id) {
        Doctors Doctors = doctorsRepository.findById(id).orElseGet(Doctors::new);
        ValidationUtil.isNull(Doctors.getId(),"Doctors","id",id);
        return doctorsMapper.toDto(Doctors);
    }

}
